package com.example.houselease.security;

import com.example.houselease.ex.ServiceException;
import com.example.houselease.mapper.AdminMapper;
import com.example.houselease.pojo.vo.AdminLoginInfoVO;
import com.example.houselease.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * spring security
 * 验证用户登录信息
 * @author xf
 * @version 0.0.1
 * */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法，参数：{}", username);

        AdminLoginInfoVO loginInfo = adminMapper.selectLoginInfoByUsername(username);
        if (loginInfo == null){
            String mes = "登录失败，用户名不存在！";
            log.warn(mes);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,mes);
        }
        log.debug("从数据库中查询到的信息，{}",loginInfo);

        List<String> permissions =loginInfo.getPermissions(); //获取管理员权限列表
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String per : permissions){
            //配置权限对象
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(per);
            authorities.add(authority);
        }

        AdminDetails adminDetails = new AdminDetails(loginInfo.getId(),
                loginInfo.getUsername(),
                loginInfo.getPassword(),
                loginInfo.getEnable() == 1,
                authorities);

        log.debug("即将向Spring Security返回UserDetails对象：{}", adminDetails);
        return adminDetails;
    }
}
